<?php

/**
 * Action Helper for loading forms
 *
 * @uses Zend_Controller_Action_Helper_Abstract
 */
class ProcessForm extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Loader_PluginLoader
     */
    public $pluginLoader;

    /**
     * Constructor: initialize plugin loader
     *
     * @return void
     */
    public function __construct()
    {
        $this->pluginLoader = new Zend_Loader_PluginLoader();
    }

	/**
	 * Puts the form into the DB, only boes a basic insert/update so if you
	 * need something morre technical then your going to have to make it
	 *
	 * @param Zend_Form $oForm
	 * @param Zend_Db_Table $oTable
	 * @param string $sAction
	 * @param string $sWhere
	 */

    public function processForm(Zend_Form $oForm, Zend_Db_Table_Abstract $oTable, $sAction)
    {
		if ($this->getRequest()->isPost())
		{
			$oFormData = $this->getRequest()->getPost();
			if ($oForm->isValid($oFormData))
			{
				$aParams = $oForm->getValues();

				switch ($sAction)
				{
					case 'insert':
						try {
							$oTable->insert($aParams);
						} catch (Zend_Db_Statement_Exception $e) {
							Zend_Registry::get('log')->crit($e->getMessage());
							return FALSE;
						}
						break;
					case 'update':
						try {
							$sWhere = $oTable->getPrimaryKeyWhereClause($aParams);
							$oTable->update($aParams, $sWhere);
						} catch (Zend_Db_Statement_Exception $e) {
							Zend_Registry::get('log')->crit($e->getMessage());
							return FALSE;
						}
						break;
				}

				return TRUE;
			} else {
				$oForm->populate($oFormData);
			}
			return FALSE;
		}
    }

	/**
	 * Strategy pattern: call helper as broker method
	 *
	 * @param Zend_Form $oForm
	 * @param Zend_Db_Table $oTable
	 * @param string $sAction
	 * @param string $sWhere
	 */
	
    public function direct(Zend_Form $oForm, Zend_Db_Table_Abstract $oTable, $sAction, $sWhere = null)
    {
        return $this->processForm($oForm, $oTable, $sAction, $sWhere);
    }
}